﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using System.Windows.Media.Media3D;

namespace WpfApplication1
{
    class MathHelper
    {
        public Vector3D normal(Point3D a, Point3D b, Point3D c)
        {
            var v1 = new Vector3D(b.X - a.X, b.Y - a.Y, b.Z - a.Z);
            var v2 = new Vector3D(c.X - b.X, c.Y - b.Y, c.Z - b.Z);
            return Vector3D.CrossProduct(v1, v2);
        }

        /*
            The ray-triangle intersection point p must be along the ray (i.e. p = o + td)
            and must be in the plane of the triangle (i.e. the vector from a triangle vertex to p
            must be perpendicular to the triangle normal), (p − a) · n = 0. From these two
            equations we get:
          0 = (p − a) · n
            = (o + td − a) · n
            = (o − a) · n + td · n
          t = (a - o) · n/(d · n)
        */
        public bool intersect(Vector3D origin, Vector3D end, Vector3D direction, Vector3D normal)
        {
            // Vector is parallel to the triangle and will result in (a-o) dot n / 0
            if (Vector3D.DotProduct(direction, normal) == 0)
                return false;

            double result = Vector3D.DotProduct(Vector3D.Subtract(end, origin), normal) / Vector3D.DotProduct(direction, normal);
            if (result < 0) // ray intersects behind origin
                return false;

            return true;
        }

        //a + u(b − a) + v(c − a) = p
        private bool barycentric(Point3D a, Point3D b, Point3D c)
        {
            Vector3D av = new Vector3D(a.X, b.X, c.X);
            Vector3D u = new Vector3D(b.X - a.X, b.Y - a.Y, b.Z - a.Z);
            Vector3D v = new Vector3D(c.X - a.X, c.Y - a.Y, c.Z - a.Z);
            Vector3D result = Vector3D.Add(av, u);
            result = Vector3D.Add(result, v);

            if (u.X >= 0 && u.Y >= 0 && u.Z >= 0 && v.X >= 0 && v.Y >= 0 && v.Z >= 0)
            {
                Vector3D uv = Vector3D.Add(u, v);
                if (uv.X <= 1 && uv.Y <= 1 && uv.Z <= 1)
                    return true;
            }

            return false;
        }
    }
}
